import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_2b_client/apis/MarketCheckInventoryRecordApi.dart';
import 'package:flutter_2b_client/components/MyPagedListView.dart';
import 'package:flutter_2b_client/components/showConfirmDialog.dart';
import 'package:flutter_2b_client/utils/MobxHooks.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';

import '../apis/MarketDeliveryOrderApi.dart';
import '../components/GoodsListItem.dart';
import '../components/LoadingButton.dart';
import '../store/EmployeeAuthorizationStore.dart';
import '../theme/custom_color.dart';
import '../utils/Page.dart';
import '../utils/PagingUtils.dart';
import '../utils/local_datetime.dart';

class MarketCheckInventoryRecordDetailPage extends HookWidget {
  final int id;

  const MarketCheckInventoryRecordDetailPage(this.id, {Key? key})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    var marketOrderDetailState =
        useState<MarketCheckInventoryRecordDetail?>(null);
    useEffect(() {
      marketCheckInventoryRecordApi
          .getMarketCheckInventoryRecordDetail(id)
          .then((value) => marketOrderDetailState.value = value);
      return null;
    }, [id]);
    var pagingController =
        usePagingController<Pageable, MarketCheckInventoryRecordItemSummary>(
            firstPageKey: Pageable());
    var totalElementsState = useState(0);
    usePagingControllerListener(
        pagingController,
        (pageable) => marketCheckInventoryRecordApi
                .queryMarketCheckInventoryRecordItems(id, pageable)
                .then((value) {
              totalElementsState.value = value.totalElements;
              return value;
            }),
        (item) => item.goodsId,
        [id]);
    final me = useObservable(
        () => Provider.of<EmployeeAuthorizationStore>(context).me);

    var showSubmitButton =
        marketOrderDetailState.value?.submittedDateTime == null &&
            me?.hasAuthority("卖场_盘点_盘点") == true;
    var showAddButton = (me?.hasAuthority("卖场_盘点_盘点") == true &&
        marketOrderDetailState.value?.submittedDateTime == null);

    return Scaffold(
      bottomNavigationBar: showAddButton || showSubmitButton
          ? BottomAppBar(
              child: Row(
                children: [
                  if (showSubmitButton)
                    LoadingButton(
                      onPressed: () async {
                        await showConfirmDialog(
                          context,
                          onConfirm: () async {
                            await marketCheckInventoryRecordApi
                                .submitMarketCheckInventoryRecord(id);
                            marketOrderDetailState.value =
                                marketOrderDetailState.value?.copyWith(
                                    submittedDateTime: LocalDateTime.now());
                            if (context.mounted) {
                              context.pop();
                            }
                          },
                          title: "是否确认",
                          content: const Text("提交后将更新库存"),
                        );
                      },
                      child: const Text("提交"),
                    ),
                  if (showAddButton)
                    IconButton(
                      onPressed: () async {
                        var goodsId = await context
                            .push(Uri(path: "/goods", queryParameters: {
                          "editMarketCheckInventoryRecordId": id.toString(),
                        }).toString()) as int?;
                        if (goodsId != null) {
                          var orderItemInOrderSummary =
                              await marketCheckInventoryRecordApi
                                  .addGoodsByGoodsId(id, goodsId);
                          pagingController.itemList = pagingController.itemList
                              ?.toList()
                            ?..add(orderItemInOrderSummary);
                          Fluttertoast.showToast(
                            msg: "添加成功！${orderItemInOrderSummary.name}",
                          );
                        }
                      },
                      icon: const Icon(Icons.add),
                    ),
                ],
              ),
            )
          : null,
      floatingActionButton: showAddButton
          ? FloatingActionButton(
              onPressed: () async {
                var barcode = (await context.push(
                  Uri(
                    path: "/scanBarcode",
                    queryParameters: {
                      "marketCheckInventoryRecordId": id.toString(),
                    },
                  ).toString(),
                )) as String?;
                if (barcode != null) {
                  var response = await marketCheckInventoryRecordApi
                      .addGoodsByGoodsBarcode(id, barcode);
                  var list = pagingController.itemList?.toList();
                  list?.add(response);
                  pagingController.itemList = list;
                  totalElementsState.value += 1;

                  Fluttertoast.showToast(
                    msg: "扫描成功！${response.name} ",
                  );
                }
              },
              child: const Icon(Icons.document_scanner),
            )
          : null,
      body: CustomScrollView(
        slivers: [
          SliverAppBar(
            expandedHeight: 120,
            pinned: true,
            title: const Text("盘点详情"),
            actions: const [],
            flexibleSpace: FlexibleSpaceBar(
              background: Padding(
                padding: const EdgeInsets.only(left: 16),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.end,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      "创建时间：${marketOrderDetailState.value?.createdDateTime.format() ?? ""}",
                    ),
                    if (marketOrderDetailState.value?.submittedDateTime != null)
                      Text(
                        "提交时间：${marketOrderDetailState.value?.submittedDateTime?.format() ?? ""}",
                      ),
                    Text(
                      "${totalElementsState.value}个单品",
                    ),
                  ],
                ),
              ),
            ),
          ),
          MyPagedSliverList(
            pagingController: pagingController,
            itemBuilder: (BuildContext context,
                MarketCheckInventoryRecordItemSummary item, int index) {
              return GestureDetector(
                onTap: () {
                  context.push("/goods/${item.goodsId}");
                },
                key: Key(item.goodsId.toString()),
                onLongPress: me?.hasAuthority("卖场_盘点_盘点") == true
                    ? () {
                        showConfirmDeleteGoodsDialog(
                          context,
                          barcode: item.barcode,
                          name: item.name,
                          onConfirm: () async {
                            await marketCheckInventoryRecordApi
                                .deleteCheckInventoryItem(id, item.goodsId);
                            deletePageItemAndSupplementOne(
                                pagingController,
                                (element) => element.goodsId != item.goodsId,
                                (pageable) async =>
                                    await marketCheckInventoryRecordApi
                                        .queryMarketCheckInventoryRecordItems(
                                            id, pageable),
                                totalElementsState);
                            if (context.mounted) {
                              Navigator.of(context).pop();
                            }
                          },
                        );
                      }
                    : null,
                child: GoodsListItem(
                  onUpdateAmount: (amount, int? unitId) async {
                    final adjustedAmount = max(amount, 0);
                    return marketCheckInventoryRecordApi
                        .updateItemAmount(id, item.goodsId,
                            UpdateItemAmountRequest(amount: adjustedAmount))
                        .then((value) {
                      Fluttertoast.showToast(
                          msg: "修改商品数量成功",
                          backgroundColor: Theme.of(context)
                              .extension<CustomColors>()
                              ?.successContainer,
                          textColor: Theme.of(context)
                              .extension<CustomColors>()
                              ?.onSuccessContainer);
                      final newList = pagingController.itemList!.toList();
                      newList[index] =
                          newList[index].copyWith(amount: adjustedAmount);
                      pagingController.itemList = newList;
                      return null;
                    });
                  },
                  edited: showAddButton || showSubmitButton,
                  name: item.name,
                  inStore: item.inStore,
                  amount: item.amount,
                  barcode: item.barcode,
                  boxSpecification: item.boxSpecification,
                ),
              );
            },
          ),
        ],
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.endContained,
    );
  }
}
